package com.ericsson.epc.modules.backup.service.impl;

import cn.hutool.extra.ssh.JschUtil;
import com.ericsson.common.util.*;
import com.ericsson.enap.modules.autoCheck.entity.NetEops;
import com.ericsson.enap.modules.backup.constant.BackupConstant;
import com.ericsson.epc.modules.backup.mapper.EpcDataBackupMapper;
import com.ericsson.epc.modules.backup.service.EpcDataBackupService;
import com.ericsson.epc.modules.backup.utils.EpcBackupUtil;
import com.ericsson.epc.modules.sys.entity.EPCNetElement;
import com.jcraft.jsch.Session;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.ericsson.enap.modules.backup.constant.BackupConstant.*;

/**
 * @description:
 * @author: wangjingshi
 * @create: 2021-07-05 09:41
 */
@Service
public class EpcDataBackupServiceImpl implements EpcDataBackupService {

    private Logger log = LoggerUtils.Logger(LogFileName.EpcDataBackupJob);

    @Autowired
    private EpcDataBackupMapper epcDataBackupMapper;

    /**
     * MME配置备份
     * @param mme
     * @param date
     */
    @Override
    public void execMmeBackup(EPCNetElement mme,String date) {
        String filePath = BackupConstant.localPath + date + "/" + mme.getType() + "/" + mme.getFname() + "/";
        SSHUtil ssh = new SSHUtil(mme.getIpadr(), mme.getUsername1(), mme.getPassword1(),log);
        try {
            ssh.connect();
            ssh.getShellChannel();
            log.info(mme.getFname()+" ==== mme backup:gsh export_config_active");
            String res = ssh.sendCommandV2("gsh export_config_active", hash,2);
            log.info(mme.getFname()+" ==== mme backup cmd result:" + res);
            res = res.substring(res.indexOf("/"),res.indexOf(mmeKey)).replaceAll("(\\x9B|\\x1B\\[|\u001B)[0-?]*[ -\\/]*[@-~]","");
            log.info(mme.getFname()+" ==== mme backup cmd result:" + res);
            log.info(mme.getFname()+" ==== mme backup :" + "cat "+res+mmeKey);
            //TODO 长沙：epc_expert@ 辽宁：ANCB ~ #
            //String result = ssh.sendCommandV3("cat "+res+mmeKey, "epc_expert@");长沙
            String result = ssh.sendCommandV3("cat "+res+mmeKey, "ANCB ~ #");
            EpcBackupUtil.writeNewFile("config.log",result,filePath+"config/");
            zipDelAndInsertDB(mme, filePath,"config");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            ssh.disconnect();
        }
    }

    /**
     * SAEGW配置备份
     * @param saegw
     * @param date
     */
    @Override
    public void execSaegwBackup(EPCNetElement saegw, String date) {
        //String filePath = BackupConstant.localPath + date + "/" + saegw.getType() + "/" + saegw.getFname() + "/";
        SSHUtil ssh = new SSHUtil(saegw.getIpadr(), saegw.getUsername1(), saegw.getPassword1(),log);
        try {
            ssh.connect();
            ssh.getShellChannel();
            log.info(saegw.getFname()+" ==== saegw backup:start shell");
            ssh.sendCommandV2("start shell", hash,1);
            ssh.sendCommandV2("start shell", dollar,1);
            /*log.info(saegw.getFname()+" ==== saegw backup:cat /flash/ericsson.xml");
            String result = ssh.sendCommandV3("cat /flash/ericsson.xml", "bash-4.3$");*/
            log.info(saegw.getFname()+" ==== saegw backup:cp /flash/ericsson.xml /flash/saegw-backup.cfg");
            ssh.sendCommandV3("cp /flash/ericsson.xml /flash/saegw-backup.cfg", "bash-4.3$");
            /*EpcBackupUtil.writeNewFile("config.log",result,filePath+"config/");
            zipDelAndInsertDB(saegw, filePath,"config");*/
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            ssh.disconnect();
        }
    }

    @Override
    public void execSaegwUBackup(EPCNetElement saegw, String date) {
        //String filePath = BackupConstant.localPath + date + "/" + saegw.getType() + "/" + saegw.getFname() + "/";
        SSHUtil ssh = new SSHUtil(saegw.getIpadr(), saegw.getUsername1(), saegw.getPassword1(),log);
        try {
            ssh.connect();
            ssh.getShellChannel();
            log.info(saegw.getFname()+" ==== saegw backup:start shell");
            ssh.sendCommandV2("start shell", hash,1);
            ssh.sendCommandV2("start shell", dollar,1);
            /*log.info(saegw.getFname()+" ==== saegw backup:cat /flash/ericsson.xml");
            String result = ssh.sendCommandV3("cat /flash/ericsson.xml", "bash-4.3$");*/
            log.info(saegw.getFname()+" ==== saegw backup:cp /flash/ericsson.xml /flash/saegw-backup.cfg");
            ssh.sendCommandV3("cp /flash/ericsson.xml /flash/saegw-backup.cfg", "bash-4.3$");
            /*EpcBackupUtil.writeNewFile("config.log",result,filePath+"config/");
            zipDelAndInsertDB(saegw, filePath,"config");*/
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            ssh.disconnect();
        }
    }
    /**
     * PCRF配置备份
     * @param pcrf
     * @param date
     */
    @Override
    public void execPcrfBackup(EPCNetElement pcrf, String date) {
        String filePath = BackupConstant.localPath + date + "/" + pcrf.getType() + "/" + pcrf.getFname() + "/";
        SSHUtil ssh = new SSHUtil(pcrf.getIpadr(), pcrf.getUsername1(), pcrf.getPassword1(),log);
        try {
            ssh.connect();
            ssh.getShellChannel();
            log.info(pcrf.getFname()+" ==== pcrf backup:cmw-status -v siass|grep -A2 com|grep SC-1 -A1");
            //TODO 辽宁移动是#号，湖南是>
            String res = ssh.sendCommandV2("cmw-status -v siass|grep -A2 com|grep SC-1 -A1", hash,2);
            log.info(pcrf.getFname()+" ==== pcrf backup result:"+res);
            String name = res.contains("ACTIVE")?"SC-1":"SC-2";
            log.info(pcrf.getFname()+" ==== pcrf backup:"+"ssh "+name);
            ssh.sendCommandV2("ssh "+name,hash,1);
            /*辽宁移动没有密码
            log.info(pcrf.getFname()+" ==== pcrf backup:"+pcrf.getPassword1());
            ssh.sendCommandV4(pcrf.getPassword1(),"~>",1);*/
            log.info(pcrf.getFname()+" ==== pcrf backup:cliss");
            ssh.sendCommandV5("cliss");
            String arr[] = {"show-config","exit","exit","exit"};
            log.info(pcrf.getFname()+" ==== pcrf backup:show-config");
            String result = ssh.sendCommands(arr);
            EpcBackupUtil.writeNewFile("config.log",result,filePath+"config/");
            zipDelAndInsertDB(pcrf, filePath,"config");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            ssh.disconnect();
        }
    }

    /**
     * CG配置备份
     * @param cg
     * @param date
     */
    @Override
    public void execCgBackup(NetEops cg, String date) {
        String filePath = BackupConstant.localPath + date + "/" + cg.getFsubtype() + "/" + cg.getFname() + "/";
        try {
            Session session = JschUtil.getSession(cg.getFaddress(), 22, cg.getFusername(), cg.getFpassword());
            log.info(cg.getFname()+" ==== cg backup:cat /etc/mediation/MM.config");
            String result = JschUtil.exec(session,"cat /etc/mediation/MM.config", Charset.forName("UTF-8"));
            JschUtil.close(session);
            EpcBackupUtil.writeNewFile("config.log",result,filePath+"config/");
            zipDelAndInsertDB(cg, filePath,"config");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {

        }
        /*SSHUtil ssh = new SSHUtil(cg.getFaddress(), cg.getFusername(), cg.getFpassword());
        try {
            ssh.connect();
            ssh.getShellChannel();
            String result = ssh.sendCommandV2("cat /etc/mediation/MM.config", "$",2);
            EpcBackupUtil.writeNewFile("config.log",result,filePath+"config/");
            zipDelAndInsertDB(cg, filePath,"config");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            ssh.disconnect();
        }*/
    }

    /**
     * MME操作日志登录日志备份
     * @param mme
     * @param date
     */
    @Override
    public void execMmeLog(EPCNetElement mme, String date,Map<String,Object> paramMap) {
        //TODO 原来湖南版本，辽宁移动需要root账户才可以
        /*String username = (String)((Map)paramMap.get("BACKUP_MME_USERNAME")).get("value");
        mme.setUsername1(username);*/
        String provinceFlag = (String)((Map)paramMap.get("PROVINCEFLAG")).get("value");
        if(provinceFlag.equals("1")){
            mme.setUsername1("sys_troubleshooter");
            mme.setPassword1("LNln1212");
        }
        String filePath = BackupConstant.localPath + date + "/" + mme.getType() + "/" + mme.getFname()+"/";
        FileUtil.newDirs(filePath+"cli_log");
        EpcBackupUtil.downloadLogBySftp(mme, filePath,"/logs/cli_log/ready/","cli_log",log);
        zipDelAndInsertDB(mme, filePath,"cli_log");
        FileUtil.newDirs(filePath+"security");
        EpcBackupUtil.downloadLogBySftp(mme, filePath,"/tmp/DPE_CORE/seclog/","security",log);
        zipDelAndInsertDB(mme, filePath,"security");
    }

    @Override
    public void execSaegwLog(EPCNetElement saegw, String date) {
        String filePath = BackupConstant.localPath + date + "/" + saegw.getType() + "/" + saegw.getFname()+"/";
        FileUtil.newDirs(filePath+"config");
        EpcBackupUtil.downloadLogBySftp(saegw, filePath,"/flash/","config",log);
        zipDelAndInsertDB(saegw, filePath,"config");

        FileUtil.newDirs(filePath+"audit");
        EpcBackupUtil.downloadLogBySftp(saegw, filePath,"/md/","audit",log);
        zipDelAndInsertDB(saegw, filePath,"audit");

        FileUtil.newDirs(filePath+"auth");
        EpcBackupUtil.downloadLogBySftp(saegw, filePath,"/var/log","auth",log);
        zipDelAndInsertDB(saegw, filePath,"auth");
    }

    @Override
    public void execPcrfLog(EPCNetElement pcrf, String date,Map<String,Object> paramMap) {
        //String password = (String)((Map)paramMap.get("BACKUP_PCRF_PASSWORD")).get("value");
        String filePath = BackupConstant.localPath + date + "/" + pcrf.getType() + "/" + pcrf.getFname() + "/";

        SSHUtil ssh = new SSHUtil(pcrf.getIpadr(), pcrf.getUsername1(), pcrf.getPassword1(),log);
        try {
            ssh.connect();
            ssh.getShellChannel();
            log.info(pcrf.getFname()+" ==== pcrf Log:last");
            //TODO 辽宁移动是#,湖南是>
            String last = ssh.sendCommandV2("last", hash,2);
            EpcBackupUtil.writeNewFile("last.log",last,filePath+"last/");
            zipDelAndInsertDB(pcrf, filePath,"last");
            /*log.info(pcrf.getFname()+" ==== pcrf Log:su -");
            ssh.sendCommandV2("su -", colon,1);
            log.info(pcrf.getFname()+" ==== pcrf Log:"+password);
            ssh.sendCommandV4(password,hash,1);*/
            log.info(pcrf.getFname()+" ==== pcrf Log:history");
            String history = ssh.sendCommandV2("history", hash,2);
            System.out.println(history);
            EpcBackupUtil.writeNewFile("history.log",history,filePath+"history/");
            zipDelAndInsertDB(pcrf, filePath,"history");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            ssh.disconnect();
        }
    }

    @Override
    public void execCgLog(NetEops cg, String date) {
        String filePath = BackupConstant.localPath + date + "/" + cg.getFsubtype() + "/" + cg.getFname() + "/";
        SSHUtil ssh = new SSHUtil(cg.getFaddress(), cg.getFusername(), cg.getFpassword(),log);
        try {
            ssh.connect();
            ssh.getShellChannel();
            //TODO 湖南sudo last方式
            /*Session session = JschUtil.getSession(cg.getFaddress(), 22, cg.getFusername(), cg.getFpassword());
            log.info(cg.getFname()+" ==== cg Log:sudo last");
            String last = JschUtil.exec(session,"sudo last", Charset.forName("UTF-8"));
            JschUtil.close(session);
            log.info(cg.getFname()+" ==== cg Log:sudo last");*/
            //TODO 辽宁sudo last需要输入密码
            ssh.sendCommand("sudo last", colon,1);
            String last = ssh.sendCommandV4(cg.getFpassword(), dollar, 1);
            //System.out.println("========last2:"+last+"==============");
            EpcBackupUtil.writeNewFile("last.log",last,filePath+"last/");
            zipDelAndInsertDB(cg, filePath,"last");
            //TimeUnit.MILLISECONDS.sleep(5000);
            /*log.info(cg.getFname()+" ==== cg Log:history");
            Session session2 = JschUtil.getSession(cg.getFaddress(), 22, cg.getFusername(), cg.getFpassword());
            String history = JschUtil.exec(session2,"history", Charset.forName("UTF-8"));
            JschUtil.close(session2);*/
            log.info(cg.getFname()+" ==== cg Log:history");
            String history = ssh.sendCommandV2("history", dollar,2);
            System.out.println("========history:"+history);
            EpcBackupUtil.writeNewFile("history.log",history,filePath+"history/");
            zipDelAndInsertDB(cg, filePath,"history");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            ssh.disconnect();
        }
    }

    @Override
    public void deleteOldData(String cleanDate) {
        epcDataBackupMapper.deleteOldData(cleanDate);
    }



    private void zipDelAndInsertDB(EPCNetElement epcNet, String filePath,String fileType) {
        String cmd = "zip -r " + filePath + fileType + ".zip" + " "+fileType;
        EpcBackupUtil.executeZipCmd(cmd, epcNet.getFname(),new File(filePath));
        File file = new File(filePath + fileType+".zip");
        String fileSize = FileSizeHelper.getHumanReadableFileSize(file.length());
        FileUtil.deleteDir(new File(filePath+fileType));
        epcDataBackupMapper.insertBackupTable(filePath,fileType+".zip", epcNet.getFname(), epcNet.getId(),Long.valueOf(epcNet.getType()),fileSize,fileType);
    }

    private void zipDelAndInsertDB(NetEops cg, String filePath,String fileType) {
        String cmd = "zip -r " + filePath + fileType + ".zip" + " "+fileType;
        EpcBackupUtil.executeZipCmd(cmd, cg.getFname(),new File(filePath));
        File file = new File(filePath + fileType+".zip");
        String fileSize = FileSizeHelper.getHumanReadableFileSize(file.length());
        FileUtil.deleteDir(new File(filePath+fileType));
        epcDataBackupMapper.insertBackupTable(filePath,fileType+".zip", cg.getFname(), Long.valueOf(cg.getId()),Long.valueOf(cg.getFsubtype()),fileSize,fileType);
    }



    public static void main(String[] args) {
        String a = "Wait!\n" +
                "Exported result: /tmp/DPE_CORE/home/epc_expert/ConfigFile_from_export\n" +
                "=== APP-HZZZhnMME01BER-01AER012 epc_expert@eqm01s0fp2 ANCB ~ # ";
        System.out.println(a.substring(a.indexOf("/"),a.indexOf(mmeKey)+mmeKey.length()));
    }
}
